package com.spboot.service.controller;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.spboot.service.entity.User;

@Controller
public class UserController {

	@Autowired
	JmsTemplate jmsTemplate;
	
	@RequestMapping("/reg")
	public String reg(User user,HttpSession session){
		
		//1添加到数据库
		user.setId((int)(Math.random() * 1000));
		session.setAttribute("user", user);
		//2 (发送邮件或短信),发送消息通知消息系统去发送短信
		jmsTemplate.convertAndSend("user_reg_msg",JSON.toJSONString(user));
		return "user_reg";
	}

	@RequestMapping("/send")
	public String send(String title){
		Connection connection = null;
		Session session = null;
		MessageProducer producer = null;
		try {
			//1.工厂
			ConnectionFactory connectionFactory = jmsTemplate.getConnectionFactory();
			//2.连接,启动
			connection = connectionFactory.createConnection();
			connection.start();
			//3.会话
			session = connection.createSession();
			//4.主题、生产者、消息
			Topic topic = session.createTopic("news_topic");
			producer = session.createProducer(topic);
			TextMessage textMessage = session.createTextMessage(title);
			//5.发送
			producer.send(textMessage);
			//关闭
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if (producer!=null) {
					producer.close();
				}
				if (session!=null) {
					session.close();
				}
				if (connection!=null) {
					connection.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		
		return "send_success";
	}
}
